/**
 * 课程数据管理Hook
 * 支持缓存机制和API请求
 */

'use client';

import { useState, useEffect, useCallback } from 'react';
import { CourseScheduleData, Course } from '../types/course';
import { ClassCoursesResponse } from '../types/api';
import { getClassCourses } from '../api/v1';
import {
  getCachedCourseData,
  setCachedCourseData,
  getCachedSelection,
  isCacheEnabled,
} from '../utils/cacheHelper';

export interface UseCourseDataReturn {
  /** 课程表数据 (包含班级信息和课程) */
  scheduleData: CourseScheduleData | null;
  /** 课程列表 */
  courses: Course[];
  /** 加载状态 */
  loading: boolean;
  /** 错误信息 */
  error: string | null;
  /** 当前学校ID */
  schoolId: number | undefined;
  /** 当前班级编号 */
  classCode: string | undefined;
  /** 是否需要选择学校/班级 */
  needsSelection: boolean;
  /** 加载课程数据 */
  loadCourseData: (schoolId: number, classCode: string) => Promise<void>;
  /** 重新加载数据 */
  reload: () => Promise<void>;
}

/**
 * 课程数据管理Hook
 * @returns 课程数据和相关状态
 */
export const useCourseData = (): UseCourseDataReturn => {
  const [scheduleData, setScheduleData] = useState<CourseScheduleData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [schoolId, setSchoolId] = useState<number | undefined>();
  const [classCode, setClassCode] = useState<string | undefined>();
  const [needsSelection, setNeedsSelection] = useState(false);

  /**
   * 从API加载课程数据
   */
  const loadFromAPI = useCallback(async (sid: number, code: string) => {
    setLoading(true);
    setError(null);
    try {
      const response: ClassCoursesResponse = await getClassCourses({
        class_code: code,
        school_id: sid,
      });

      // 转换API响应为CourseScheduleData格式
      const data: CourseScheduleData = {
        class_info: response.class_info,
        courses: response.courses as Course[],
      };

      setScheduleData(data);
      setSchoolId(sid);
      setClassCode(code);
      setNeedsSelection(false);

      // 保存到缓存
      setCachedCourseData(sid, code, response);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '加载课程数据失败';
      setError(errorMessage);
      console.error('Failed to load course data:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 初始化加载逻辑
   */
  const initializeData = useCallback(async () => {
    setLoading(true);
    setError(null);

    try {
      // 检查缓存
      const cached = getCachedCourseData();

      if (cached) {
        // 缓存有效,使用缓存数据
        const data: CourseScheduleData = {
          class_info: cached.data.class_info,
          courses: cached.data.courses as Course[],
        };
        setScheduleData(data);
        setSchoolId(cached.school_id);
        setClassCode(cached.class_code);
        setNeedsSelection(false);
        setLoading(false);
      } else {
        // 缓存无效,检查是否有缓存的选择信息
        const selection = getCachedSelection();
        
        if (selection.school_id && selection.class_code) {
          // 有选择信息但缓存过期,重新加载
          await loadFromAPI(selection.school_id, selection.class_code);
        } else {
          // 没有任何信息,需要用户选择
          setNeedsSelection(true);
          setLoading(false);
        }
      }
    } catch (err) {
      console.error('Failed to initialize data:', err);
      setNeedsSelection(true);
      setLoading(false);
    }
  }, [loadFromAPI]);

  /**
   * 加载课程数据(外部调用)
   */
  const loadCourseData = useCallback(
    async (sid: number, code: string) => {
      await loadFromAPI(sid, code);
    },
    [loadFromAPI]
  );

  /**
   * 重新加载当前数据
   */
  const reload = useCallback(async () => {
    if (schoolId && classCode) {
      await loadFromAPI(schoolId, classCode);
    } else {
      await initializeData();
    }
  }, [schoolId, classCode, loadFromAPI, initializeData]);

  // 组件挂载时初始化
  useEffect(() => {
    initializeData();
  }, [initializeData]);

  return {
    scheduleData,
    courses: scheduleData?.courses || [],
    loading,
    error,
    schoolId,
    classCode,
    needsSelection,
    loadCourseData,
    reload,
  };
};
